package top.lyc829.mymusic.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import top.lyc829.mymusic.model.http.AppException
import top.lyc829.mymusic.model.http.ExceptionHandle

/**
 * @Author lyc
 * @create 2021-07-06 17:05
 */
open class BaseViewModel : ViewModel() {
    var isLoading = MutableLiveData<Boolean>()

    val errorLiveData = MutableLiveData<AppException>()

    fun launch(
        loading: Boolean = false,
        block: suspend () -> Unit,
        error: suspend (AppException) -> Unit,
        complete: suspend () -> Unit
    ) {
        viewModelScope.launch {
            try {
                isLoading.value = loading
                block()
            } catch (e: Exception) {
                error(ExceptionHandle.handleException(e))
            } finally {
                isLoading.value = false
                complete()
            }
        }
    }

    fun launch(
        loading: Boolean = false,
        block: suspend () -> Unit,
        error: suspend (AppException) -> Unit
    ) {
        viewModelScope.launch {
            try {
                isLoading.value = loading
                block()
            } catch (e: Exception) {
                error(ExceptionHandle.handleException(e))
            } finally {
                isLoading.value = false
            }
        }
    }

}